/**
 * @file 后台接口文件
 *
 * @author fanxingguang
 * 2016-10-31
 */
'use strict';
const _ = require('lodash');
const modelUser = require('../../models/user');
const Captchapng = require('captchapng');
const md5 = require('md5');
const DATA = {
    msg: '',
    code: 0,
    data: ''
};

module.exports = {
    get: {
        getAllUsers(req, res) {
            let data = _.clone(DATA);
            modelUser.find((err, result) => {
                data.data = result;
                res.json(data);
            });
        },
        getCaptcha(req, res) {
            let width = !isNaN(parseInt(req.query.width, 10)) ? parseInt(req.query.width, 10) : 100;
            let height = !isNaN(parseInt(req.query.height, 10)) ? parseInt(req.query.height, 10) : 30;

            let code = parseInt(Math.random() * 9000 + 1000, 10);
            req.session.checkcode = code;

            let p = new Captchapng(width, height, code);
            p.color(0, 0, 0, 0);
            p.color(80, 80, 80, 255);

            let img = p.getBase64();
            let imgbase64 = new Buffer(img, 'base64');
            res.writeHead(200, {
                'Content-Type': 'image/png'
            });
            res.end(imgbase64);
        }
    },
    post: {
        doLogin(req, res) {
            let data = _.clone(DATA);
            data.code = 1;
            if (req.session.checkcode + '' !== +req.body.captcha + '') {
                data.code = 1;
                data.msg = '验证码有误';
                res.json(data);
                return;
            }
            modelUser.findOne({username: req.body.username}, (err, doc) => {
                if (!doc) {
                    data.msg = '用户名错误！';
                }
                else if (doc.password !== md5(req.body.password)) {
                    data.msg = '密码错误！';
                }
                else {
                    data.code = 0;
                    data.msg = '';
                    data.data = {
                        userid: doc.username._id,
                        username: doc.username
                    };
                }
                res.json(data);
            });
        }
    }
};
